#coding=utf-8
from stutils import set_django_environ, get_dbconnector
set_django_environ()

from stdj.stock.models import *
import datetime
td = datetime.date.today().isoformat()

def get_con():
    from stsettings import datadir
    return get_dbconnector('%s/price.db'%datadir)
    
tb_price = '''
create table if not exists price
(id integer primary key,
 code text not null,
 name text not null,
 
 date text not null,
 
 start real not null,
 end real not null,
 high real not null,
 low real not null,
 
 volume integer not null,
 amount integer not null,
 change real,
 hsl real,
 fluctuation real not null,
 
 unique (code, date)
);'''

def adayprice2db(cursor, exday):
    e = exday
    s = e.share
    p = e.price
    
    cursor.execute('insert into price (code, name, date, start, end, high, low, fluctuation, volume, amount)\
                    values(?,?,?,?,?,?,?,?,?,?)', 
                    (s.code, s.name, e.date, 
                        float(p.start), float(p.end), float(p.high), float(p.low), float(p.fluctuation),
                        p.volume,p.amount)
                    )
                    
    if p.change:
        cursor.execute('update price set change=? where code=? and date=?',
                        (float(p.change), s.code, e.date),
                        )
    if p.hsl:
        cursor.execute('update price set hsl=? where code=? and date=?',
                        (float(p.hsl), s.code, e.date),
                        )
                        
def initdb(con):
    cursor = con.cursor()
    cursor.execute(tb_price)
    
    for s in Share.objects.order_by('code'):
        eds = s.exday_set.filter(date__gte='2005-01-01').order_by('date')
        print s,len(eds)
        
        for e in eds:
            adayprice2db(cursor, e)
        con.commit()
        
def updatedb(con):
    cursor = con.cursor()
    
    for s in Share.objects.order_by('code'):
        
        if s.created_at.isoformat() == td:
            for e in s.exday_set.filter(date__gte='2004-01-01').order_by('date'):
                adayprice2db(cursor, e)
            con.commit()    
            continue
        
        try:
            e = s.exday_set.get(date=td)
        except Exday.DoesNotExist,e:
            pass
        else:
            print e
            adayprice2db(cursor, e)
    con.commit()
    
if __name__ == "__main__":
    con = get_con()
    initdb(con)
